layui.use(['table','layer','form','element'], function(){
    var table = layui.table;
    var layer = layui.layer;
    var $ = layui.jquery;
    var form = layui.form;
    var element = layui.element;

    var funcList = {
        //添加单个主机
        "hostAdd":function(){
            currentIndex = layer.open({
                type : 1,
                title : '添加主机信息',
                area : [ '400px', '495px' ],
                content : '<div id="add-server-form"></div>',
                success : function(index, layero) {
                    $('#add-server-form').load('add-host.html', function() {
                    	form.render('select');
                    	var host_submit = funcList["hostSubmit"];
                    	host_submit();
                    })

                }
            });
        },
        //监听主机添加表单提交
        "hostSubmit":function(){
        	form.on('submit(add-confirm)',function(data){
        		var ipcheck = funcList["checkIp"];     		
        		if(!ipcheck()){
        			layer.msg("ip地址不合法",{icon:2,time:1000});
        			return false;
        		}
        		var loadindex = layer.msg('正在保存中...', {
        			icon : 16,
        			time : 99999,
        			shade : 0.4
        		});
        		//提交表单数据到后台
        		$.ajax({
        			type : "POST",
        			url : "add.do",
        			data : data.field,
        			success : function(msg) {
        				layer.close(loadindex);
        				if (msg == 1) {
        					layer.close(currentIndex);
        					var tablereload = funcList["loadHostList"];
        					tablereload();
        					layer.msg("保存成功", {
        						icon : 1,
        						time : 1800
        					});	
        				}
        				else{
        					layer.msg("保存失败", {
        						icon : 2,
        						time : 1800
        					});
        				}
        			}
        		});
        		//主机添加页面提交表单数据			
        		return false;
        	})
        },
        //批量添加主机弹层
        "multihostAdd":function(){
            multiIndex = layer.open({
                type : 1,
                title : '批量添加主机',
                skin:'layui-layer-lan',
                area : [ '605px', '335px' ],
                content : '<div id="multi-server-form" class="layui-form" lay-filter="test1"></div>',
                success : function(index, layero) {
                    $('#multi-server-form').load('multiadd-host.html',
                        function() {
                            form.render(null,'test1');
                            $("#multiConfirm").click(function(){
                            	var multiAdd = funcList["muliAddHost"];
                            	multiAdd();
                            })
                            
                        })

                }
            });
        },
        //批量添加主机提交
        "muliAddHost":function(){
        	var textValue = $("#hostsText").val();
        	var loadindex = layer.msg('正在保存中...', {
				icon : 16,
				time : 99999,
				shade : 0.4
			});
        	$.ajax({
				type : "POST",
				url : "multiadd.do",
				data : {hostslist:textValue},
				dataType:"json",
				success : function(msg) {
					layer.close(loadindex);
					if (msg[1] >= 1) {
						layer.close(multiIndex);
						var func = funcList["loadHostList"];
						func();
						layer.open({
							  title: '执行结果'
							  ,area:['100px','200px']
							  ,content: '添加总数:'+msg[0]+"<br>"+"成功总数:"+msg[1]+"<br>"+"失败总数:"+msg[2]
							  ,btn:""
							  ,skin:"layui-layer-molv"
							});   
						
					}
					else{
						layer.msg("保存失败", {
							icon : 2,
							time : 1800
						});
					}
				}
			});	
        	
        },
        //批量删除按钮
        "multiDelete":function(){
        	//校验是否选择主机
        	var checkStatus = table.checkStatus('allHostList'); //test即为基础参数id对应的值
			var length =  checkStatus.data.length;
			
			//定义一个数组用于存储所选主机的id值
			var hostids = new Array();
			for(var i=0;i < length;i++){
				//获取选中行的id
				hostids.push(JSON.stringify(checkStatus.data[i].id));
			}
			
			if( length == 0){
				layer.msg("未选择任何主机",{icon:2,time:2000});
			}else{	
				var msg = "确定删除所选的 "+length+"台主机吗?"
				layer.confirm(msg, {icon: 3, title:'提示'}, function(index){
					layer.close(index);
					var loadindex = layer.msg('删除中,请稍后...', {
						icon : 16,
						time : 99999,
						shade : 0.4
					});  
					$.ajax({
					type : "POST",
					url : "multidel.do",
					data : {hostinfos:hostids.toString()},
					success : function(msg) {
						   layer.close(loadindex); 
						   var tablereload = funcList["loadHostList"];
						   tablereload();
						}
					});
					  
				});
			}
			
        },
        //命令执行按钮
        "commandExec":function(){
        	var checkStatus = table.checkStatus("allHostList"); //test即为基础参数id对应的值
			var length =  checkStatus.data.length;
			if( length == 0){
				layer.msg("请先指定主机",{icon:2,time:2000});
			}else{
				cmdIndex = layer.open({
	                type : 1,
	                title : '命令执行窗口 [当前主机数:'+length+']',
	                skin:'layui-layer-molv',
	                area : [ '605px', '535px' ],
	                content : '<div id="commandExec-form" class="layui-form" lay-filter="test1"></div>',
	                success : function(index, layero) {
	                    $('#commandExec-form').load('commd-exec.html',
	                        function() {
	                    	 form.render(null,'test1');
	                    	 $("#cmdExec").click(function(){
	                    		//定义一个数组用于存储所选主机的id值
	                 			var hostids = new Array();
	                 			for(var i=0;i < length;i++){
	                 				//获取选中行的id
	                 				hostids.push(JSON.stringify(checkStatus.data[i].id));
	                 			}
	                    		var cmdexec = funcList["cmdExecBtn"];
	                    		cmdexec(hostids);
	                    		 
	                    	 })
	                    	 
	                       })

	                }
	            });
			}   
        },
      //开始执行按钮
        "cmdExecBtn":function(hostids){
        	var cmdVaule = $("#command").val();
        	if( cmdVaule ==  ""){
        		layer.msg("命令内容不能为空!!!",{icon:2,time:1000});
        	}else{
        		var loadindex = layer.msg('命令执行中...', {
					icon : 16,
					time : 99999,
					shade : 0.4
				});
				
				$.ajax({
					type : "POST",
					url : "cmdexec.do",
					data : {hostinfos:hostids.toString(), cmd:cmdVaule},
					success : function(msg) {
						   layer.close(loadindex);
						   $("#cmdResMsg").val(msg);
						}
					});
        	}	
        }, 
      //主机管理页面搜索框重载表格
		"search-btn":function(){
			var loadindex = layer.msg('玩命加载中...', {
				icon : 16,
				time : 99999,
				shade : 0.4
			});
			var keyValue = $('#key-value');
			table.reload('allHostList',{
					page:true,
					limit:10000,
					limits:[10000],
					where:{searchkey: keyValue.val()},
					done:function(){
						layer.close(loadindex);
					}
				})
		},
		"tableReload":function(){
			var loadindex = layer.msg('玩命加载中...', {
				icon : 16,
				time : 99999,
				shade : 0.4
			});
			table.reload('allHostList',{
					//page:{curr:1},
					done:function(){
						layer.close(loadindex);
					}
				})
		},
		//主机配置页面表格渲染
		"loadHostList":function(){
			 var loadindex = layer.msg('正在加载中...', {
					icon : 16,
					time : 999999,
					shade : 0.4
				});
			    table.render({
			        elem: '#hosts-table'
			        //,url: '../data/user' //数据接口
			        ,url:'get.do'
			        ,page: true //开启分页
			        ,limit:14
			        ,limits:[14,20,30,40,50,60,100]
			        ,cols: [[ //表头
			            {checkbox : true,fixed : true}
			            ,{field: 'id', title: 'ID', width:70, sort: true, align:'center'}
			            ,{field: 'host_group', title: '主机分组', width:110,align:'center'}
			            ,{field: 'host_type', title: '主机类型', width:130, align:'center'}
			            ,{field: 'ip_address', title: '主机地址', width:130, align:'center'}
			            ,{field: 'login_name', title: '用户名', width: 110,align : 'center'}
			            ,{field: 'login_pwd', title: '密码', width: 110, align : 'center'}
			            ,{field: 'login_port', title: '端口', width: 90, align : 'center'}
			            ,{field: 'conn_status', title: '连接状态', width: 100,align : 'center',templet: '#connStatus'}
			            ,{field: 'create_time', title: '创建时间', width: 150,align : 'center'}
			            ,{field: 'modify_time', title: '修改时间', width: 150,align : 'center'}
			            ,{field: 'mark', title: '备注', width: 205,align : 'center'}
			            ,{field: 'operation', title: '主机操作', width: 279,align : 'center',toolbar : '#barDemo'}
			        ]],
			        id : 'allHostList',
			        height:627,
			        done:function(){
			            layer.close(loadindex);
			        }
			    });	
	
		},
		//输入框对ip地址进行校验
		"checkIp":function(){
			var ip = $("#hostip").val();
			var exp=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
			var reg = ip.match(exp);
			if( reg == null){	
				return false;
			}
			return true;
			
		},
		//监听表格复选框是否被选中
		"chkBox":function(tableid){
			var checkStatus = table.checkStatus(tableid); //test即为基础参数id对应的值
			var length =  checkStatus.data.length;
			if( length == 0){
				layer.msg("未选择任何主机",{icon:2,time:2000});
			}
		},
		//删除主机信息
		"delete":function(obj,data,index){
			$.ajax({
				type : "POST",
				url : "del.do",
				data : data,
				success : function(msg) {
					if( msg == 1){
						obj.del();
						layer.close(index);
					}else{
						layer.msg("服务异常，删除失败!!");
					}
						
					
				}
			});
		},
		//主机重连方法
		"reConn":function(data,index){
			$.ajax({
				type : "POST",
				url : "reconn.do",
				data : data,
				success : function(msg) {
					if( msg == 1){
						table.reload('allHostList',{
							done:function(){
								layer.close(index);
								var func = funcList["tableReload"];
								func();
							}
						})
					}else{
						layer.msg("操作数据库失败!!!",{icon:2,time:1000});
					}
					
				}
			});
		},

    }
//-------------方法列表结束-------------------------------------------
    
    //加载主机配置页面的主机列表
	var func = funcList["loadHostList"];
    func();
   
    //监听按钮动作
    $(".active-btn").click(function(){
        var id = $(this).attr("id");
        if( id != null){
     	   var func = funcList[id];
            func();
        }else{
     	   layer.msg("功能尚未定义");
        }
    })
   
    // 监听工具条
	table.on('tool(hostInfo)', function(obj) {
		var data = obj.data;
		if (obj.event === 'reConn') {
			if( data.conn_status == 0){
				layer.msg('当前主机可连接');
			}else{
				var index = layer.msg('玩命重连中...',{icon:16,time:9999999});
				var func = funcList[obj.event];
				func(data,index);
			}			
			
		} else if (obj.event === 'delete') {
			layer.confirm('确定删除吗？', function(index) {
				var func = funcList[obj.event];
				func(obj,data,index);
			});
		} else if (obj.event === 'edit') {
			layer.alert('编辑行：<br>' + JSON.stringify(data))
		}
	});
    
});